package com.zerowidth.moc.web.pay.lt;

import com.zerowidth.moc.web.utils.EncryptUtils;
import com.zerowidth.moc.web.utils.StringUtils;
import okhttp3.OkHttpClient;
import org.apache.commons.codec.Charsets;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.TimeUnit;

public class LTPayOrderFactory {

    private static final String TAG = "LTPayOrderFactory";

    private static final String URL = "https://api.ltzf.cn";


    private static String MCH_ID = "1671877602";
    private static String SECRET = "c1d675b9965c94539b531d9e8ad90b79";

    /**
     * @param payType
     * @param subject
     * @param outTradeNo
     * @param notifyUrl
     * @param amount     支付金额，单位：分
     */
    public static LTOrderBean createOrderInfo(int payType, String subject, String outTradeNo,
                                              String notifyUrl, float amount) {
        String body = subject;
        body = outTradeNo; //产品标题使用订单号，防止被微信冻结
        String mch_id = MCH_ID;
        String notify_url = notifyUrl;
        String total_fee = String.valueOf(amount);
        String out_trade_no = outTradeNo;
        String timestamp = String.valueOf(System.currentTimeMillis() / 1000);

        String postData = "body=" + body + "&mch_id=" + mch_id + "&notify_url=" + notify_url
                + "&out_trade_no=" + out_trade_no + "&timestamp=" + timestamp + "&total_fee=" + total_fee;

        String signData = postData + "&key=" + SECRET;
        String sign = EncryptUtils.encryptMD5ToString(signData);

        LTOrderBean orderBean = new LTOrderBean();
        orderBean.userName = "gh_40a6af82554e";
        orderBean.path = "pages/pay/pay?" + postData + "&sign=" + sign + "&title=蓝兔支付";

        return orderBean;
    }

    private static OkHttpClient getOkHttpClient() {
        OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder();

        long timeOut = 20_000;

        okHttpClientBuilder.callTimeout(timeOut, TimeUnit.MILLISECONDS);
        okHttpClientBuilder.connectTimeout(timeOut, TimeUnit.MILLISECONDS);
        okHttpClientBuilder.writeTimeout(timeOut, TimeUnit.MILLISECONDS);
        okHttpClientBuilder.readTimeout(timeOut, TimeUnit.MILLISECONDS);

        return okHttpClientBuilder.build();
    }

    public static String createSign(Map<String, String> params) throws NoSuchAlgorithmException {
        // 生成签名前先去除sign
        params.remove("sign");
        String stringA = packageSign(params, false);
        String stringSignTemp = stringA + "&key=" + SECRET;

        // 计算 MD5 签名
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        md5.update(stringSignTemp.getBytes());
        byte[] digest = md5.digest();

        // 将字节数组转换为十六进制字符串
        StringBuilder signature = new StringBuilder();
        for (byte b : digest) {
            signature.append(String.format("%02x", b));
        }
        return signature.toString().toUpperCase();
    }

    public static String packageSign(Map<String, String> params, boolean urlEncoder) {
        // 先将参数以其参数名的字典序升序进行排序
        TreeMap<String, String> sortedParams = new TreeMap<String, String>(params);
        // 遍历排序后的字典，将所有参数按"key=value"格式拼接在一起
        StringBuilder sb = new StringBuilder();
        boolean first = true;
        for (Map.Entry<String, String> param : sortedParams.entrySet()) {
            String value = param.getValue();
            if (StringUtils.isEmpty(value)) {
                continue;
            }
            if (first) {
                first = false;
            } else {
                sb.append("&");
            }
            sb.append(param.getKey()).append("=");
            if (urlEncoder) {
                try {
                    value = urlEncode(value);
                } catch (UnsupportedEncodingException e) {
                }
            }
            sb.append(value);
        }
        return sb.toString();
    }

    public static String urlEncode(String src) throws UnsupportedEncodingException {
        return URLEncoder.encode(src, Charsets.UTF_8.name()).replace("+", "%20");
    }


}
